`timescale 1ns / 1ps 
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 2022/03/02 20:38:03
// Design Name:
// Module Name: difference
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////


module difference(clk,
                  resetb,
                  ie,
                  idat,
                  oe,
                  odat, sel,
                  cmd,
                  T_DAT

                 );
parameter ADDR_MAX = 800 * 600;
input clk;
input resetb;
input ie;
input [15: 0] idat;
output oe;
output odat;
output sel;
input cmd;
input [9: 0] T_DAT;
parameter ck2q = 1;
reg cmd_d0;
always@(posedge clk or negedge resetb)
	begin
		if (!resetb)
			cmd_d0 <= #ck2q 0;
		else
			cmd_d0 <= #ck2q cmd;
	end
reg [18: 0] addr;
wire addr_tc = (addr + 1'b1 == ADDR_MAX);
always@(posedge clk or negedge resetb)
	begin
		if (!resetb)
			addr <= #ck2q 0;
		else if (ie)
			begin
				if (addr_tc)
					addr <= #ck2q 0;
				else
					addr <= #ck2q addr + 1'b1;
			end
	end
reg sel;
always@(posedge clk or negedge resetb)
	begin
		if (!resetb)
			sel <= 0;
		else if (ie & addr_tc)
			sel <= ~sel;
	end
reg [8: 0] T;
always@(posedge clk or negedge resetb)
	begin
		if (!resetb)
			T <= #ck2q 9'd40;
		else if ((cmd | cmd_d0) & (T_DAT[9: 8] == 2'd2))
			T <= #ck2q {1'b0, T_DAT[7: 0]};
	end
wire [8: 0] dat_act = idat[15: 8];
wire [8: 0] dat_back = idat[ 7: 0];
reg odat;
always@(posedge clk or negedge resetb)
	begin
		if (!resetb)
			odat <= #ck2q 0;
		else if (ie & ( (dat_act + T) < dat_back ) | ( (dat_back + T) < dat_back ) )
			odat <= #ck2q 1'b0;
		else
			odat <= #ck2q 1'b1;
	end
reg oe;
always@(posedge clk or negedge resetb)
	begin
		if (!resetb)
			oe <= #ck2q 0;
		else
			oe <= #ck2q ie;
	end
endmodule
